package com.yami.shop.mystery.platform.task;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.ActivityRemoveChangeStatusEvent;
import com.yami.shop.bean.event.EsMysteryBoxStockUpdateEvent;
import com.yami.shop.bean.model.SkuStock;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.mystery.common.dto.ActivityProdDataDto;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.ActivityProd;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.model.MysteryBoxExtension;
import com.yami.shop.mystery.common.service.*;
import com.yami.shop.service.SkuStockService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 盲盒订单的定时任务
 *
 * @author wxf
 * @date 2023/4/13 15:52
 */
@Component
@AllArgsConstructor
public class MysteryBoxOrderTask {

    private final MysteryBoxService mysteryBoxService;
    private final MysteryBoxOrderService mysteryBoxOrderService;
    private final MysteryBoxExtensionService mysteryBoxExtensionService;
    private final ActivityPresellService activityPresellService;
    private final ActivityProdService activityProdService;
    private final ApplicationEventPublisher eventPublisher;
    private final SkuStockService skuStockService;
    private final MysteryBoxOpenRecordService recordService;
    private final MysteryBoxUserArkService mysteryBoxUserArkService;

    /**
     * 盲盒下架，回退商品库存
     */
    @XxlJob("mysteryBoxFinish")
    public void mysteryBoxFinish(){
        // 查询所有已删除，还有库存的盲盒商品
        List<MysteryBox> list = mysteryBoxService.selectDelist();

        for (MysteryBox box : list) {
            //  校验盲盒是否已开完，没开发，本次不执行，等待开盲盒定时任务开盲盒，完了以后再回退库存
            long userArk = mysteryBoxUserArkService.countByBid(box.getId());

            if (userArk > 0) { // 用户持有盲盒与初始化盲盒数不相等，还有盲盒未初始化，还不能回退库存
                continue;
            }

            List<MysteryBoxExtension> extensionList = mysteryBoxExtensionService.findExtensionByBoxId(box.getId());
            List<SkuStock> ids = new ArrayList<>();
            for (MysteryBoxExtension extension : extensionList) {
                if (extension.getPid() == -1) {
                    mysteryBoxExtensionService.rollbackStocks(extension);
                    continue;
                }
                List<SkuStock> skuList = skuStockService.listSkuStockByProdId(extension.getPid());
                if (CollectionUtils.isEmpty(skuList) || skuList.size() != 1) {
                    // 商品库存不足，不能参加盲盒活动
                    throw new YamiShopBindException("下架盲盒商品id:" + extension.getBid() + "获取商品id:" + extension.getPid() + " 的库存信息不存在，无法回退商品库存");
                }
                SkuStock stock = skuList.get(0);
                stock.setLockStock(extension.getStocks());
                stock.setStockId(extension.getId());
                ids.add(stock);
            }
            if (CollectionUtils.isNotEmpty(ids)) {
                EsMysteryBoxStockUpdateEvent event = new EsMysteryBoxStockUpdateEvent(box.getId(), ids, EsOperationType.DELETE_BATCH, null);
                eventPublisher.publishEvent(event);
            }
        }
    }

    /**
     * 预售活动结束，改变商品类型
     */
    @XxlJob("activityPresellFinish")
    public void activityPresellFinish(){
        // 失效时已经回退库存，这里不做处理，只处理活动时间到，还生效的数据
        List<ActivityPresell> activityPresellList = activityPresellService.list(new LambdaQueryWrapper<ActivityPresell>()
                .lt(ActivityPresell::getActivityEndTime, new Date())
                .eq(ActivityPresell::getDelFlag, 0)
                .eq(ActivityPresell::getStatus, 0)
                .in(ActivityPresell::getActivityType, 1, 3,4)
        );
        if (activityPresellList.size() > 0){
            List<Long> activityIds = Lists.newArrayList();
            Map<Long, String> mapType = new HashMap<>();
            Map<Long, Long> mapBoxType = new HashMap<>();
            for (ActivityPresell presell: activityPresellList){
                activityIds.add(presell.getId());
                mapType.put(presell.getId(), presell.getActivityType());
                if(presell.getActivityType().equals("4")){
                    mapBoxType.put(presell.getId(),presell.getBlindType());
                }
            }

            UpdateWrapper<ActivityPresell> wrapper = new UpdateWrapper<>();
            wrapper.in("id",activityIds);
            wrapper.set("status",4);
            activityPresellService.update(wrapper);
        }
    }
}
